#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <errno.h>
#include "typedef.h"
#include "package.h"

#define BUF_LEN PACKAGE_LEN

static int sockfd = 0;
static struct sockaddr_in server_addr;
static struct hostent *host;

int net_open(char* ip, int port)
{
    if (ip == NULL || *ip == '\0')
        return ERROR;

    host = gethostbyname(ip);
    if (host == NULL)
        return ERROR;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
        return FATAL;

    bzero(&server_addr, sizeof(struct sockaddr_in));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port   = htons(port);
    server_addr.sin_addr   = *((struct in_addr *)host->h_addr);

    if (connect(sockfd, (struct sockaddr*)(&server_addr), sizeof(struct sockaddr)) == -1)
        return ERROR;

    return SUCCESS;
}

void net_close()
{
    close(sockfd);
}

int net_send(char* data, int size)
{
    if (sockfd == 0 || data == NULL)
        return ERROR;
    if (write(sockfd, data, size) == -1)
        return FATAL;
    return SUCCESS;
}

int net_read(char* buffer, int buflen, int *readsize)
{
	int  size;
	char temp[BUF_LEN];

    if (buffer == NULL || readsize == NULL)
        return FATAL;

    *readsize = 0;

    while(TRUE)
    {
    	size = read(sockfd, temp, BUF_LEN);
    	if (size < 0)
    	{
    		if (errno == EINTR)
    			size = 0;
    		else
    			return ERROR;
    	}
    	else
    	{
    		arraycopy(buffer, 0, temp, 0, size);
    		*readsize = size;
			break;
    	}
    }

    return SUCCESS;
}

